package com.demo.base.redis.redisson.delayQueue;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 消息发送端
 * @date 2023/3/30 11:36 PM
 */
@Component
@Slf4j
public class UnpaidOrderQueue {

    /** 注入 RedissonClient */
    private RedissonClient redissonClient;

    @Autowired
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 添加消息到延时队列
     *
     * <p>自定义延迟时间，单位：ms
     *
     * @param orderId
     */
    public void addUnpaidDelay(String orderId, Integer delayTime) {

        RBlockingQueue<String> blockingFairQueue =
                redissonClient.getBlockingQueue("orderDelayQueue");
        RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);

        log.info(DateTime.now().toString("yyyy-MM-dd HH:mm:ss") + "，添加任务到延时队列，订单号：{}", orderId);
        delayedQueue.offer(orderId, delayTime, TimeUnit.MILLISECONDS);
    }
}
